#include "CubeEmitter.h"
#include "TextureLoader.h"
#include <cstdlib>
#include <ctime>
#include <iostream>

int CubeEmitter::randomInt(int max)
{
//	srand((unsigned)time(0));
	return rand() % max;
}

void CubeEmitter::emit(float timeD, CubePile * cubePiles [][GRID_SIZE], GLuint topTextures[NUM_TEXTURES], GLuint sideTextures [NUM_TEXTURES])
{
    timeSinceLastEmission += (int)timeD;
//    cout << "timeD = " << timeD << " total time = " << timeSinceLastEmission << " nextEmissionTime:" << nextEmissionTime << " emissionsLeft:" << emissionsLeft << "\n";
    if (emissionsLeft > 0 && timeSinceLastEmission > nextEmissionTime)
    {
        int x = randomInt(GRID_SIZE);
		int z = randomInt(GRID_SIZE);
		CubePile * cubePile = cubePiles[x][z];
        
		if(cubePile->size() < MAX_CUBES_IN_PILE)
		{
		
	//    	cout << "emitting x:" << x << " z:" << z << "\n";
		    emit(x,z, cubePile, topTextures, sideTextures);
		    
	        timeSinceLastEmission = 0;
	        nextEmissionTime = randomInt(maxEmitTime);
	        if(nextEmissionTime < MIN_EMIT_TIME)
		    {
		    	nextEmissionTime = MIN_EMIT_TIME;	
		    }
	        emissionsLeft--;	
		    
		    if(emissionsLeft == 0)
		    {
		    	cout << "no more cubes to emit" << "\n";
		    }
		}
    }
	
}

void CubeEmitter::emit(int x, int z, CubePile * cubePile, GLuint topTextures[NUM_TEXTURES], GLuint sideTextures [NUM_TEXTURES])
{
	int randomTexture = randomInt(NUM_TEXTURES);
	Cube * cube = new Cube(topTextures[randomTexture], sideTextures[randomTexture]);
	cube->xPos = x* (2 + CUBE_GAP);
	cube->yPos = CUBE_Y_DROP;
	cube->zPos = z* (2 + CUBE_GAP);
	cubePile->dropCube(cube);
}


CubeEmitter::CubeEmitter(int aMaxEmitTime, int aMaxEmissions)
{
	maxEmitTime = aMaxEmitTime;
    nextEmissionTime = randomInt(maxEmitTime);
    if(nextEmissionTime < MIN_EMIT_TIME)
    {
    	nextEmissionTime = MIN_EMIT_TIME;	
    }
    emissionsLeft = aMaxEmissions;
    timeSinceLastEmission = 0;
}

CubeEmitter::~CubeEmitter()
{
	
}

